#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
#include "logger.hpp"

namespace zzy_mims
{
    using server_t =websocketpp::server<websocketpp::config::asio>;


    class Connection
    {
    public:
        struct Client
        {
            Client(){};
            Client(const std::string& uid,const std::string& sid)
            :_uid(uid),_sid(sid){};
            std::string _uid;
            std::string _sid;
        };
        using ptr = std::shared_ptr<Connection>;
        Connection(){};
        ~Connection(){};


        void insert(const server_t::connection_ptr& conn,const std::string& uid,const std::string& sid)
        {
            std::unique_lock<std::mutex> lock(_mutex);

            _uid_connections[uid] = conn;
            _conn_clients[conn] = Client(uid,sid);
            LOG_DEBUG("新增长连接用户信息->{}:{}-{}",(size_t)conn.get(),uid,sid);
        };
        server_t::connection_ptr connection(const std::string& uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);

            if(!_uid_connections.count(uid))
            {
                LOG_ERROR("未找到{}客户端的长连接",uid);
                return server_t::connection_ptr();
            }
            LOG_DEBUG("找到{}客户端的长连接",uid);
            return _uid_connections[uid];

        };
        bool client(const server_t::connection_ptr& conn,std::string& uid,std::string& sid)
        {
            std::unique_lock<std::mutex> lock(_mutex);

            if(!_conn_clients.count(conn))
            {
                LOG_ERROR("查询-未找到连接:{}对应的客户端",(size_t)conn.get());
                return false;
            }
            uid = _conn_clients[conn]._uid;
            sid = _conn_clients[conn]._sid;
            LOG_DEBUG("找到连接:{}对应的客户端",(size_t)conn.get());
            return true;
        };
        void remove(const server_t::connection_ptr& conn)
        {
            std::unique_lock<std::mutex> lock(_mutex);

            if(!_conn_clients.count(conn))
            {
                LOG_ERROR("删除-未找到连接:{}对应的客户端",(size_t)conn.get());
                return;
            }
            string uid = _conn_clients[conn]._uid;
            _conn_clients.erase(conn);
            _uid_connections.erase(uid);
            LOG_DEBUG("删除长连接:{}",(size_t)conn.get());
        };

    private:
        std::mutex _mutex;
        std::unordered_map<std::string,server_t::connection_ptr> _uid_connections;
        std::unordered_map<server_t::connection_ptr,Client> _conn_clients;
    };
}